package com.ChengXiZi.controller.admin;

import com.ChengXiZi.constant.JwtClaimsConstant;
import com.ChengXiZi.dto.SysadminLoginDto;
import com.ChengXiZi.entity.User;
import com.ChengXiZi.properties.JwtProperties;
import com.ChengXiZi.result.Result;
import com.ChengXiZi.service.SysadminService;

import com.ChengXiZi.utils.JwtUtil;
import com.ChengXiZi.vo.SysadminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 系统管理员接口
 */
@RestController
@RequestMapping("/sysadmin")
@Slf4j
@Api(tags = "系统管理员接口")
public class SysadminContruller {

    @Autowired
    private SysadminService sysadminService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 系统管理员登录
     * @param sysadminLoginDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("系统管理员登录")
    public Result<SysadminLoginVO> login (@RequestBody SysadminLoginDto sysadminLoginDto){
        log.info("系统管理员登录：{}",sysadminLoginDto);

        //实际为系统管理员
        User user = sysadminService.login(sysadminLoginDto);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        SysadminLoginVO sysadminLoginVO = SysadminLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();

        return Result.success(sysadminLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("管理员退出")
    public Result<String> logout() {
        return Result.success();
    }

    /**
     * 封禁普通用户账号
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("封禁普通用户账号")
    public Result startOrStop(@PathVariable Integer status, Long id){
        log.info("封禁普通用户账号：status：{},id：{}",status,id);
        sysadminService.startOrStop(status,id);
        return Result.success();
    }
}
